3 * This is the Oracle database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\Blob
;
26 use Wikimedia\Rdbms\ResultWrapper
;
27 use Wikimedia\Rdbms\DBConnectionError
;
28 use Wikimedia\Rdbms\DBUnexpectedError
;
33 class DatabaseOracle
extends Database
{
35 protected $mLastResult = null;
37 /** @var int The number of rows affected as an integer */
38 protected $mAffectedRows;
41 private $ignoreDupValOnIndex = false;
43 /** @var bool|array */
44 private $sequenceData = null;
46 /** @var string Character set for Oracle database */
47 private $defaultCharset = 'AL32UTF8';
50 private $mFieldInfoCache = [];
52 function __construct( array $p ) {
55 if ( $p['tablePrefix'] == 'get from global' ) {
56 $p['tablePrefix'] = $wgDBprefix;
58 $p['tablePrefix'] = strtoupper( $p['tablePrefix'] );
59 parent
::__construct( $p );
60 Hooks
::run( 'DatabaseOraclePostInit', [ $this ] );
63 function __destruct() {
64 if ( $this->opened
) {
65 Wikimedia\
suppressWarnings();
67 Wikimedia\restoreWarnings
();
75 function implicitGroupby() {
79 function implicitOrderby() {
84 * Usually aborts on failure
85 * @param string $server
87 * @param string $password
88 * @param string $dbName
89 * @throws DBConnectionError
90 * @return resource|null
92 function open( $server, $user, $password, $dbName ) {
93 global $wgDBOracleDRCP;
94 if ( !function_exists( 'oci_connect' ) ) {
95 throw new DBConnectionError(
97 "Oracle functions missing, have you compiled PHP with the --with-oci8 option?\n " .
98 "(Note: if you recently installed PHP, you may need to restart your webserver\n " .
104 $this->password
= $password;
105 // changed internal variables functions
106 // mServer now holds the TNS endpoint
107 // mDBname is schema name if different from username
109 // backward compatibillity (server used to be null and TNS was supplied in dbname)
110 $this->server
= $dbName;
111 $this->dbName
= $user;
113 $this->server
= $server;
115 $this->dbName
= $user;
117 $this->dbName
= $dbName;
121 if ( !strlen( $user ) ) { # e.g. the class is being loaded
125 if ( $wgDBOracleDRCP ) {
126 $this->setFlag( DBO_PERSISTENT
);
129 $session_mode = $this->flags
& DBO_SYSDBA ? OCI_SYSDBA
: OCI_DEFAULT
;
131 Wikimedia\
suppressWarnings();
132 if ( $this->flags
& DBO_PERSISTENT
) {
133 $this->conn
= oci_pconnect(
137 $this->defaultCharset
,
140 } elseif ( $this->flags
& DBO_DEFAULT
) {
141 $this->conn
= oci_new_connect(
145 $this->defaultCharset
,
149 $this->conn
= oci_connect(
153 $this->defaultCharset
,
157 Wikimedia\restoreWarnings
();
159 if ( $this->user
!= $this->dbName
) {
160 // change current schema in session
161 $this->selectDB( $this->dbName
);
164 if ( !$this->conn
) {
165 throw new DBConnectionError( $this, $this->lastError() );
168 $this->opened
= true;
170 # removed putenv calls because they interfere with the system globaly
171 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
172 $this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
173 $this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
179 * Closes a database connection, if it is open
180 * Returns success, true if already closed
183 protected function closeConnection() {
184 return oci_close( $this->conn
);
187 function execFlags() {
188 return $this->trxLevel ? OCI_NO_AUTO_COMMIT
: OCI_COMMIT_ON_SUCCESS
;
191 protected function doQuery( $sql ) {
192 wfDebug( "SQL: [$sql]\n" );
193 if ( !StringUtils
::isUtf8( $sql ) ) {
194 throw new InvalidArgumentException( "SQL encoding is invalid\n$sql" );
197 // handle some oracle specifics
198 // remove AS column/table/subquery namings
199 if ( !$this->getFlag( DBO_DDLMODE
) ) {
200 $sql = preg_replace( '/ as /i', ' ', $sql );
203 // Oracle has issues with UNION clause if the statement includes LOB fields
204 // So we do a UNION ALL and then filter the results array with array_unique
205 $union_unique = ( preg_match( '/\/\* UNION_UNIQUE \*\/ /', $sql ) != 0 );
206 // EXPLAIN syntax in Oracle is EXPLAIN PLAN FOR and it return nothing
207 // you have to select data from plan table after explain
208 $explain_id = MWTimestamp
::getLocalInstance()->format( 'dmYHis' );
212 'EXPLAIN PLAN SET STATEMENT_ID = \'' . $explain_id . '\' FOR',
218 Wikimedia\
suppressWarnings();
220 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
221 if ( $stmt === false ) {
222 $e = oci_error( $this->conn
);
223 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
228 if ( !oci_execute( $stmt, $this->execFlags() ) ) {
229 $e = oci_error( $stmt );
230 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
231 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
237 Wikimedia\restoreWarnings
();
239 if ( $explain_count > 0 ) {
240 return $this->doQuery( 'SELECT id, cardinality "ROWS" FROM plan_table ' .
241 'WHERE statement_id = \'' . $explain_id . '\'' );
242 } elseif ( oci_statement_type( $stmt ) == 'SELECT' ) {
243 return new ORAResult( $this, $stmt, $union_unique );
245 $this->mAffectedRows
= oci_num_rows( $stmt );
251 function queryIgnore( $sql, $fname = '' ) {
252 return $this->query( $sql, $fname, true );
256 * Frees resources associated with the LOB descriptor
257 * @param ResultWrapper|ORAResult $res
259 function freeResult( $res ) {
260 if ( $res instanceof ResultWrapper
) {
268 * @param ResultWrapper|ORAResult $res
271 function fetchObject( $res ) {
272 if ( $res instanceof ResultWrapper
) {
276 return $res->fetchObject();
280 * @param ResultWrapper|ORAResult $res
283 function fetchRow( $res ) {
284 if ( $res instanceof ResultWrapper
) {
288 return $res->fetchRow();
292 * @param ResultWrapper|ORAResult $res
295 function numRows( $res ) {
296 if ( $res instanceof ResultWrapper
) {
300 return $res->numRows();
304 * @param ResultWrapper|ORAResult $res
307 function numFields( $res ) {
308 if ( $res instanceof ResultWrapper
) {
312 return $res->numFields();
315 function fieldName( $stmt, $n ) {
316 return oci_field_name( $stmt, $n );
319 function insertId() {
320 $res = $this->query( "SELECT lastval_pkg.getLastval FROM dual" );
321 $row = $this->fetchRow( $res );
322 return is_null( $row[0] ) ?
null : (int)$row[0];
329 function dataSeek( $res, $row ) {
330 if ( $res instanceof ORAResult
) {
333 $res->result
->seek( $row );
337 function lastError() {
338 if ( $this->conn
=== false ) {
341 $e = oci_error( $this->conn
);
344 return $e['message'];
347 function lastErrno() {
348 if ( $this->conn
=== false ) {
351 $e = oci_error( $this->conn
);
357 protected function fetchAffectedRowCount() {
358 return $this->mAffectedRows
;
362 * Returns information about an index
363 * If errors are explicitly ignored, returns NULL on failure
364 * @param string $table
365 * @param string $index
366 * @param string $fname
369 function indexInfo( $table, $index, $fname = __METHOD__
) {
373 function indexUnique( $table, $index, $fname = __METHOD__
) {
377 function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
378 if ( !count( $a ) ) {
382 if ( !is_array( $options ) ) {
383 $options = [ $options ];
386 if ( in_array( 'IGNORE', $options ) ) {
387 $this->ignoreDupValOnIndex
= true;
390 if ( !is_array( reset( $a ) ) ) {
394 foreach ( $a as &$row ) {
395 $this->insertOneRow( $table, $row, $fname );
399 if ( in_array( 'IGNORE', $options ) ) {
400 $this->ignoreDupValOnIndex
= false;
406 private function fieldBindStatement( $table, $col, &$val, $includeCol = false ) {
407 $col_info = $this->fieldInfoMulti( $table, $col );
408 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
411 if ( is_numeric( $col ) ) {
416 } elseif ( $includeCol ) {
420 if ( $val == '' && $val !== 0 && $col_type != 'BLOB' && $col_type != 'CLOB' ) {
424 if ( $val === 'NULL' ) {
428 if ( $val === null ) {
429 if ( $col_info != false && $col_info->isNullable() == 0 && $col_info->defaultValue() != null ) {
442 * @param string $table
444 * @param string $fname
446 * @throws DBUnexpectedError
448 private function insertOneRow( $table, $row, $fname ) {
451 $table = $this->tableName( $table );
452 // "INSERT INTO tables (a, b, c)"
453 $sql = "INSERT INTO " . $table . " (" . implode( ',', array_keys( $row ) ) . ')';
456 // for each value, append ":key"
458 foreach ( $row as $col => &$val ) {
464 if ( $this->isQuotedIdentifier( $val ) ) {
465 $sql .= $this->removeIdentifierQuotes( $val );
468 $sql .= $this->fieldBindStatement( $table, $col, $val );
473 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
474 if ( $stmt === false ) {
475 $e = oci_error( $this->conn
);
476 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
480 foreach ( $row as $col => &$val ) {
481 $col_info = $this->fieldInfoMulti( $table, $col );
482 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
484 if ( $val === null ) {
485 // do nothing ... null was inserted in statement creation
486 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
487 if ( is_object( $val ) ) {
488 $val = $val->fetch();
491 // backward compatibility
492 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
493 $val = $this->getInfinity();
496 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
497 if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR
) === false ) {
498 $e = oci_error( $stmt );
499 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
504 /** @var OCI_Lob[] $lob */
505 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
506 if ( $lob[$col] === false ) {
507 $e = oci_error( $stmt );
508 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
511 if ( is_object( $val ) ) {
512 $val = $val->fetch();
515 if ( $col_type == 'BLOB' ) {
516 $lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB
);
517 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB
);
519 $lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB
);
520 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
525 Wikimedia\
suppressWarnings();
527 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
528 $e = oci_error( $stmt );
529 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
530 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
534 $this->mAffectedRows
= oci_num_rows( $stmt );
537 $this->mAffectedRows
= oci_num_rows( $stmt );
540 Wikimedia\restoreWarnings
();
542 if ( isset( $lob ) ) {
543 foreach ( $lob as $lob_v ) {
548 if ( !$this->trxLevel
) {
549 oci_commit( $this->conn
);
552 return oci_free_statement( $stmt );
555 function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__
,
556 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
558 $destTable = $this->tableName( $destTable );
560 $sequenceData = $this->getSequenceData( $destTable );
561 if ( $sequenceData !== false &&
562 !isset( $varMap[$sequenceData['column']] )
564 $varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
567 // count-alias subselect fields to avoid abigious definition errors
569 foreach ( $varMap as &$val ) {
570 $val = $val . ' field' . ( $i++
);
573 $selectSql = $this->selectSQLText(
575 array_values( $varMap ),
582 $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' . $selectSql;
584 if ( in_array( 'IGNORE', $insertOptions ) ) {
585 $this->ignoreDupValOnIndex
= true;
588 $retval = $this->query( $sql, $fname );
590 if ( in_array( 'IGNORE', $insertOptions ) ) {
591 $this->ignoreDupValOnIndex
= false;
597 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
600 if ( !count( $rows ) ) {
601 return true; // nothing to do
604 if ( !is_array( reset( $rows ) ) ) {
608 $sequenceData = $this->getSequenceData( $table );
609 if ( $sequenceData !== false ) {
610 // add sequence column to each list of columns, when not set
611 foreach ( $rows as &$row ) {
612 if ( !isset( $row[$sequenceData['column']] ) ) {
613 $row[$sequenceData['column']] =
614 $this->addIdentifierQuotes( 'GET_SEQUENCE_VALUE(\'' .
615 $sequenceData['sequence'] . '\')' );
620 return parent
::upsert( $table, $rows, $uniqueIndexes, $set, $fname );
623 function tableName( $name, $format = 'quoted' ) {
625 Replace reserved words with better ones
626 Using uppercase because that's the only way Oracle can handle
634 $name = 'PAGECONTENT';
638 return strtoupper( parent
::tableName( $name, $format ) );
641 function tableNameInternal( $name ) {
642 $name = $this->tableName( $name );
644 return preg_replace( '/.*\.(.*)/', '$1', $name );
648 * Return sequence_name if table has a sequence
650 * @param string $table
653 private function getSequenceData( $table ) {
654 if ( $this->sequenceData
== null ) {
655 $result = $this->doQuery( "SELECT lower(asq.sequence_name),
656 lower(atc.table_name),
657 lower(atc.column_name)
658 FROM all_sequences asq, all_tab_columns atc
661 '{$this->tablePrefix}MWUSER',
662 '{$this->tablePrefix}USER',
665 atc.column_name || '_SEQ' = '{$this->tablePrefix}' || asq.sequence_name
666 AND asq.sequence_owner = upper('{$this->dbName}')
667 AND atc.owner = upper('{$this->dbName}')" );
669 while ( ( $row = $result->fetchRow() ) !== false ) {
670 $this->sequenceData
[$row[1]] = [
671 'sequence' => $row[0],
676 $table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
678 return ( isset( $this->sequenceData
[$table] ) ) ?
$this->sequenceData
[$table] : false;
682 * Returns the size of a text field, or -1 for "unlimited"
684 * @param string $table
685 * @param string $field
688 function textFieldSize( $table, $field ) {
689 $fieldInfoData = $this->fieldInfo( $table, $field );
691 return $fieldInfoData->maxLength();
694 function limitResult( $sql, $limit, $offset = false ) {
695 if ( $offset === false ) {
699 return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
702 function encodeBlob( $b ) {
703 return new Blob( $b );
706 function decodeBlob( $b ) {
707 if ( $b instanceof Blob
) {
714 function unionQueries( $sqls, $all ) {
715 $glue = ' UNION ALL ';
717 return 'SELECT * ' . ( $all ?
'' : '/* UNION_UNIQUE */ ' ) .
718 'FROM (' . implode( $glue, $sqls ) . ')';
721 function wasDeadlock() {
722 return $this->lastErrno() == 'OCI-00060';
725 function duplicateTableStructure( $oldName, $newName, $temporary = false,
728 $temporary = $temporary ?
'TRUE' : 'FALSE';
730 $newName = strtoupper( $newName );
731 $oldName = strtoupper( $oldName );
733 $tabName = substr( $newName, strlen( $this->tablePrefix
) );
734 $oldPrefix = substr( $oldName, 0, strlen( $oldName ) - strlen( $tabName ) );
735 $newPrefix = strtoupper( $this->tablePrefix
);
737 return $this->doQuery( "BEGIN DUPLICATE_TABLE( '$tabName', " .
738 "'$oldPrefix', '$newPrefix', $temporary ); END;" );
741 function listTables( $prefix = null, $fname = __METHOD__
) {
743 if ( !empty( $prefix ) ) {
744 $listWhere = ' AND table_name LIKE \'' . strtoupper( $prefix ) . '%\'';
747 $owner = strtoupper( $this->dbName
);
748 $result = $this->doQuery( "SELECT table_name FROM all_tables " .
749 "WHERE owner='$owner' AND table_name NOT LIKE '%!_IDX\$_' ESCAPE '!' $listWhere" );
751 // dirty code ... i know
753 $endArray[] = strtoupper( $prefix . 'MWUSER' );
754 $endArray[] = strtoupper( $prefix . 'PAGE' );
755 $endArray[] = strtoupper( $prefix . 'IMAGE' );
756 $fixedOrderTabs = $endArray;
757 while ( ( $row = $result->fetchRow() ) !== false ) {
758 if ( !in_array( $row['table_name'], $fixedOrderTabs ) ) {
759 $endArray[] = $row['table_name'];
766 public function dropTable( $tableName, $fName = __METHOD__
) {
767 $tableName = $this->tableName( $tableName );
768 if ( !$this->tableExists( $tableName ) ) {
772 return $this->doQuery( "DROP TABLE $tableName CASCADE CONSTRAINTS PURGE" );
775 function timestamp( $ts = 0 ) {
776 return wfTimestamp( TS_ORACLE
, $ts );
780 * Return aggregated value function call
782 * @param array $valuedata
783 * @param string $valuename
786 public function aggregateValue( $valuedata, $valuename = 'value' ) {
791 * @return string Wikitext of a link to the server software's web site
793 public function getSoftwareLink() {
794 return '[{{int:version-db-oracle-url}} Oracle]';
798 * @return string Version information from the database
800 function getServerVersion() {
801 // better version number, fallback on driver
802 $rset = $this->doQuery(
803 'SELECT version FROM product_component_version ' .
804 'WHERE UPPER(product) LIKE \'ORACLE DATABASE%\''
806 $row = $rset->fetchRow();
808 return oci_server_version( $this->conn
);
811 return $row['version'];
815 * Query whether a given index exists
816 * @param string $table
817 * @param string $index
818 * @param string $fname
821 function indexExists( $table, $index, $fname = __METHOD__
) {
822 $table = $this->tableName( $table );
823 $table = strtoupper( $this->removeIdentifierQuotes( $table ) );
824 $index = strtoupper( $index );
825 $owner = strtoupper( $this->dbName
);
826 $sql = "SELECT 1 FROM all_indexes WHERE owner='$owner' AND index_name='{$table}_{$index}'";
827 $res = $this->doQuery( $sql );
829 $count = $res->numRows();
839 * Query whether a given table exists (in the given schema, or the default mw one if not given)
840 * @param string $table
841 * @param string $fname
844 function tableExists( $table, $fname = __METHOD__
) {
845 $table = $this->tableName( $table );
846 $table = $this->addQuotes( strtoupper( $this->removeIdentifierQuotes( $table ) ) );
847 $owner = $this->addQuotes( strtoupper( $this->dbName
) );
848 $sql = "SELECT 1 FROM all_tables WHERE owner=$owner AND table_name=$table";
849 $res = $this->doQuery( $sql );
850 if ( $res && $res->numRows() > 0 ) {
862 * Function translates mysql_fetch_field() functionality on ORACLE.
863 * Caching is present for reducing query time.
864 * For internal calls. Use fieldInfo for normal usage.
865 * Returns false if the field doesn't exist
867 * @param array|string $table
868 * @param string $field
869 * @return ORAField|ORAResult|false
871 private function fieldInfoMulti( $table, $field ) {
872 $field = strtoupper( $field );
873 if ( is_array( $table ) ) {
874 $table = array_map( [ $this, 'tableNameInternal' ], $table );
875 $tableWhere = 'IN (';
876 foreach ( $table as &$singleTable ) {
877 $singleTable = $this->removeIdentifierQuotes( $singleTable );
878 if ( isset( $this->mFieldInfoCache
["$singleTable.$field"] ) ) {
879 return $this->mFieldInfoCache
["$singleTable.$field"];
881 $tableWhere .= '\'' . $singleTable . '\',';
883 $tableWhere = rtrim( $tableWhere, ',' ) . ')';
885 $table = $this->removeIdentifierQuotes( $this->tableNameInternal( $table ) );
886 if ( isset( $this->mFieldInfoCache
["$table.$field"] ) ) {
887 return $this->mFieldInfoCache
["$table.$field"];
889 $tableWhere = '= \'' . $table . '\'';
892 $fieldInfoStmt = oci_parse(
894 'SELECT * FROM wiki_field_info_full WHERE table_name ' .
895 $tableWhere . ' and column_name = \'' . $field . '\''
897 if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
898 $e = oci_error( $fieldInfoStmt );
899 $this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__
);
903 $res = new ORAResult( $this, $fieldInfoStmt );
904 if ( $res->numRows() == 0 ) {
905 if ( is_array( $table ) ) {
906 foreach ( $table as &$singleTable ) {
907 $this->mFieldInfoCache
["$singleTable.$field"] = false;
910 $this->mFieldInfoCache
["$table.$field"] = false;
912 $fieldInfoTemp = null;
914 $fieldInfoTemp = new ORAField( $res->fetchRow() );
915 $table = $fieldInfoTemp->tableName();
916 $this->mFieldInfoCache
["$table.$field"] = $fieldInfoTemp;
920 return $fieldInfoTemp;
924 * @throws DBUnexpectedError
925 * @param string $table
926 * @param string $field
929 function fieldInfo( $table, $field ) {
930 if ( is_array( $table ) ) {
931 throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
934 return $this->fieldInfoMulti( $table, $field );
937 protected function doBegin( $fname = __METHOD__
) {
939 $this->doQuery( 'SET CONSTRAINTS ALL DEFERRED' );
942 protected function doCommit( $fname = __METHOD__
) {
943 if ( $this->trxLevel
) {
944 $ret = oci_commit( $this->conn
);
946 throw new DBUnexpectedError( $this, $this->lastError() );
949 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
953 protected function doRollback( $fname = __METHOD__
) {
954 if ( $this->trxLevel
) {
955 oci_rollback( $this->conn
);
957 $this->doQuery( 'SET CONSTRAINTS ALL IMMEDIATE' );
961 function sourceStream(
963 callable
$lineCallback = null,
964 callable
$resultCallback = null,
965 $fname = __METHOD__
, callable
$inputCallback = null
969 $dollarquote = false;
972 // Defines must comply with ^define\s*([^\s=]*)\s*=\s?'\{\$([^\}]*)\}';
973 while ( !feof( $fp ) ) {
974 if ( $lineCallback ) {
975 call_user_func( $lineCallback );
977 $line = trim( fgets( $fp, 1024 ) );
978 $sl = strlen( $line ) - 1;
983 if ( '-' == $line[0] && '-' == $line[1] ) {
987 // Allow dollar quoting for function declarations
988 if ( substr( $line, 0, 8 ) == '/*$mw$*/' ) {
989 if ( $dollarquote ) {
990 $dollarquote = false;
991 $line = str_replace( '/*$mw$*/', '', $line ); // remove dollarquotes
996 } elseif ( !$dollarquote ) {
997 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
999 $line = substr( $line, 0, $sl );
1009 $cmd = str_replace( ';;', ";", $cmd );
1010 if ( strtolower( substr( $cmd, 0, 6 ) ) == 'define' ) {
1011 if ( preg_match( '/^define\s*([^\s=]*)\s*=\s*\'\{\$([^\}]*)\}\'/', $cmd, $defines ) ) {
1012 $replacements[$defines[2]] = $defines[1];
1015 foreach ( $replacements as $mwVar => $scVar ) {
1016 $cmd = str_replace( '&' . $scVar . '.', '`{$' . $mwVar . '}`', $cmd );
1019 $cmd = $this->replaceVars( $cmd );
1020 if ( $inputCallback ) {
1021 call_user_func( $inputCallback, $cmd );
1023 $res = $this->doQuery( $cmd );
1024 if ( $resultCallback ) {
1025 call_user_func( $resultCallback, $res, $this );
1028 if ( false === $res ) {
1029 $err = $this->lastError();
1031 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
1043 function selectDB( $db ) {
1044 $this->dbName
= $db;
1045 if ( $db == null ||
$db == $this->user
) {
1048 $sql = 'ALTER SESSION SET CURRENT_SCHEMA=' . strtoupper( $db );
1049 $stmt = oci_parse( $this->conn
, $sql );
1050 Wikimedia\
suppressWarnings();
1051 $success = oci_execute( $stmt );
1052 Wikimedia\restoreWarnings
();
1054 $e = oci_error( $stmt );
1055 if ( $e['code'] != '1435' ) {
1056 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1065 function strencode( $s ) {
1066 return str_replace( "'", "''", $s );
1069 function addQuotes( $s ) {
1071 if ( isset( $wgContLang->mLoaded
) && $wgContLang->mLoaded
) {
1072 $s = $wgContLang->checkTitleEncoding( $s );
1075 return "'" . $this->strencode( $s ) . "'";
1078 public function addIdentifierQuotes( $s ) {
1079 if ( !$this->getFlag( DBO_DDLMODE
) ) {
1086 public function removeIdentifierQuotes( $s ) {
1087 return strpos( $s, '/*Q*/' ) === false ?
$s : substr( $s, 5 );
1090 public function isQuotedIdentifier( $s ) {
1091 return strpos( $s, '/*Q*/' ) !== false;
1094 private function wrapFieldForWhere( $table, &$col, &$val ) {
1097 $col_info = $this->fieldInfoMulti( $table, $col );
1098 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1099 if ( $col_type == 'CLOB' ) {
1100 $col = 'TO_CHAR(' . $col . ')';
1101 $val = $wgContLang->checkTitleEncoding( $val );
1102 } elseif ( $col_type == 'VARCHAR2' ) {
1103 $val = $wgContLang->checkTitleEncoding( $val );
1107 private function wrapConditionsForWhere( $table, $conds, $parentCol = null ) {
1109 foreach ( $conds as $col => $val ) {
1110 if ( is_array( $val ) ) {
1111 $conds2[$col] = $this->wrapConditionsForWhere( $table, $val, $col );
1113 if ( is_numeric( $col ) && $parentCol != null ) {
1114 $this->wrapFieldForWhere( $table, $parentCol, $val );
1116 $this->wrapFieldForWhere( $table, $col, $val );
1118 $conds2[$col] = $val;
1125 function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1126 $options = [], $join_conds = []
1128 if ( is_array( $conds ) ) {
1129 $conds = $this->wrapConditionsForWhere( $table, $conds );
1132 return parent
::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
1136 * Returns an optional USE INDEX clause to go after the table, and a
1137 * string to go at the end of the query
1139 * @param array $options An associative array of options to be turned into
1140 * an SQL query, valid keys are listed in the function.
1143 function makeSelectOptions( $options ) {
1144 $preLimitTail = $postLimitTail = '';
1148 foreach ( $options as $key => $option ) {
1149 if ( is_numeric( $key ) ) {
1150 $noKeyOptions[$option] = true;
1154 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1156 $preLimitTail .= $this->makeOrderBy( $options );
1158 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1159 $postLimitTail .= ' FOR UPDATE';
1162 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1163 $startOpts .= 'DISTINCT';
1166 if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
1167 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1172 if ( isset( $options['IGNORE INDEX'] ) && !is_array( $options['IGNORE INDEX'] ) ) {
1173 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1178 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1181 public function delete( $table, $conds, $fname = __METHOD__
) {
1182 global $wgActorTableSchemaMigrationStage;
1184 if ( is_array( $conds ) ) {
1185 $conds = $this->wrapConditionsForWhere( $table, $conds );
1187 // a hack for deleting pages, users and images (which have non-nullable FKs)
1188 // all deletions on these tables have transactions so final failure rollbacks these updates
1189 // @todo: Normalize the schema to match MySQL, no special FKs and such
1190 $table = $this->tableName( $table );
1191 if ( $table == $this->tableName( 'user' ) && $wgActorTableSchemaMigrationStage < MIGRATION_NEW
) {
1192 $this->update( 'archive', [ 'ar_user' => 0 ],
1193 [ 'ar_user' => $conds['user_id'] ], $fname );
1194 $this->update( 'ipblocks', [ 'ipb_user' => 0 ],
1195 [ 'ipb_user' => $conds['user_id'] ], $fname );
1196 $this->update( 'image', [ 'img_user' => 0 ],
1197 [ 'img_user' => $conds['user_id'] ], $fname );
1198 $this->update( 'oldimage', [ 'oi_user' => 0 ],
1199 [ 'oi_user' => $conds['user_id'] ], $fname );
1200 $this->update( 'filearchive', [ 'fa_deleted_user' => 0 ],
1201 [ 'fa_deleted_user' => $conds['user_id'] ], $fname );
1202 $this->update( 'filearchive', [ 'fa_user' => 0 ],
1203 [ 'fa_user' => $conds['user_id'] ], $fname );
1204 $this->update( 'uploadstash', [ 'us_user' => 0 ],
1205 [ 'us_user' => $conds['user_id'] ], $fname );
1206 $this->update( 'recentchanges', [ 'rc_user' => 0 ],
1207 [ 'rc_user' => $conds['user_id'] ], $fname );
1208 $this->update( 'logging', [ 'log_user' => 0 ],
1209 [ 'log_user' => $conds['user_id'] ], $fname );
1210 } elseif ( $table == $this->tableName( 'image' ) ) {
1211 $this->update( 'oldimage', [ 'oi_name' => 0 ],
1212 [ 'oi_name' => $conds['img_name'] ], $fname );
1215 return parent
::delete( $table, $conds, $fname );
1219 * @param string $table
1220 * @param array $values
1221 * @param array $conds
1222 * @param string $fname
1223 * @param array $options
1225 * @throws DBUnexpectedError
1227 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1230 $table = $this->tableName( $table );
1231 $opts = $this->makeUpdateOptions( $options );
1232 $sql = "UPDATE $opts $table SET ";
1235 foreach ( $values as $col => &$val ) {
1236 $sqlSet = $this->fieldBindStatement( $table, $col, $val, true );
1239 $sqlSet = ', ' . $sqlSet;
1246 if ( $conds !== [] && $conds !== '*' ) {
1247 $conds = $this->wrapConditionsForWhere( $table, $conds );
1248 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1251 $this->mLastResult
= $stmt = oci_parse( $this->conn
, $sql );
1252 if ( $stmt === false ) {
1253 $e = oci_error( $this->conn
);
1254 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1258 foreach ( $values as $col => &$val ) {
1259 $col_info = $this->fieldInfoMulti( $table, $col );
1260 $col_type = $col_info != false ?
$col_info->type() : 'CONSTANT';
1262 if ( $val === null ) {
1263 // do nothing ... null was inserted in statement creation
1264 } elseif ( $col_type != 'BLOB' && $col_type != 'CLOB' ) {
1265 if ( is_object( $val ) ) {
1266 $val = $val->getData();
1269 if ( preg_match( '/^timestamp.*/i', $col_type ) == 1 && strtolower( $val ) == 'infinity' ) {
1270 $val = '31-12-2030 12:00:00.000000';
1273 $val = ( $wgContLang != null ) ?
$wgContLang->checkTitleEncoding( $val ) : $val;
1274 if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
1275 $e = oci_error( $stmt );
1276 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1281 /** @var OCI_Lob[] $lob */
1282 $lob[$col] = oci_new_descriptor( $this->conn
, OCI_D_LOB
);
1283 if ( $lob[$col] === false ) {
1284 $e = oci_error( $stmt );
1285 throw new DBUnexpectedError( $this, "Cannot create LOB descriptor: " . $e['message'] );
1288 if ( is_object( $val ) ) {
1289 $val = $val->getData();
1292 if ( $col_type == 'BLOB' ) {
1293 $lob[$col]->writeTemporary( $val );
1294 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB
);
1296 $lob[$col]->writeTemporary( $val );
1297 oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB
);
1302 Wikimedia\
suppressWarnings();
1304 if ( oci_execute( $stmt, $this->execFlags() ) === false ) {
1305 $e = oci_error( $stmt );
1306 if ( !$this->ignoreDupValOnIndex ||
$e['code'] != '1' ) {
1307 $this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__
);
1311 $this->mAffectedRows
= oci_num_rows( $stmt );
1314 $this->mAffectedRows
= oci_num_rows( $stmt );
1317 Wikimedia\restoreWarnings
();
1319 if ( isset( $lob ) ) {
1320 foreach ( $lob as $lob_v ) {
1325 if ( !$this->trxLevel
) {
1326 oci_commit( $this->conn
);
1329 return oci_free_statement( $stmt );
1332 function bitNot( $field ) {
1333 // expecting bit-fields smaller than 4bytes
1334 return 'BITNOT(' . $field . ')';
1337 function bitAnd( $fieldLeft, $fieldRight ) {
1338 return 'BITAND(' . $fieldLeft . ', ' . $fieldRight . ')';
1341 function bitOr( $fieldLeft, $fieldRight ) {
1342 return 'BITOR(' . $fieldLeft . ', ' . $fieldRight . ')';
1345 function getDBname() {
1346 return $this->dbName
;
1349 function getServer() {
1350 return $this->server
;
1353 public function buildGroupConcatField(
1354 $delim, $table, $field, $conds = '', $join_conds = []
1356 $fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
1358 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1361 public function buildSubstring( $input, $startPosition, $length = null ) {
1362 $this->assertBuildSubstringParams( $startPosition, $length );
1363 $params = [ $input, $startPosition ];
1364 if ( $length !== null ) {
1365 $params[] = $length;
1367 return 'SUBSTR(' . implode( ',', $params ) . ')';
1371 * @param string $field Field or column to cast
1375 public function buildStringCast( $field ) {
1376 return 'CAST ( ' . $field . ' AS VARCHAR2 )';
1379 public function getInfinity() {
1380 return '31-12-2030 12:00:00.000000';